<template>
  <!-- 制芯月计划实际表表单弹窗 -->
  <div>
    <el-dialog
      v-model="visibleDialog"
      :title="props.title"
      width="1200px"
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="100"
      >
        <h4 class="mb-[20px] mt-[0px]">基本数据</h4>
        <div>
          <el-row>
            <el-col :span="6">
              <el-form-item label="产品名称">
                <el-input v-model="formData.materialName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="产品编号">
                <el-input v-model="formData.materialCode" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="砂芯编号">
                <el-input v-model="formData.sandCoreNumber" disabled />
              </el-form-item>
            </el-col>
            <!--<el-col :span="6">
              <el-form-item label="总套数">
                <el-input v-model="formData.allTotal" disabled />
              </el-form-item>
            </el-col>-->
            <el-col :span="6">
              <el-form-item label="件/M">
                <el-input v-model="formData.pm" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="M/S">
                <el-input v-model="formData.ms" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="冷芯/热芯">
                <el-input v-model="formData.coreState" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="设备型号">
                <el-input v-model="formData.equipModel" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="砂型号">
                <el-input v-model="formData.sandModel" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="需求人数">
                <el-input v-model="formData.demandPeople" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="计划数量" prop="planQuantity">
                <el-input v-model="formData.planQuantity" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="已排数量" prop="finishQuantity">
                <el-input v-model="formData.finishQuantity" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="日期" prop="requireDate">
                <el-input v-model="formData.requireDate" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="总时长/S">
                <el-input v-model="formData.totalTime" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="班制" prop="shiftSetId">
                <el-select
                  v-model="formData.shiftSetId"
                  placeholder="请选择班制"
                  @change="changeShiftSet"
                  clearable
                >
                  <el-option
                    v-for="item in shiftSetList"
                    :key="item.id"
                    :label="item.shiftSetName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="班组" prop="crewId">
                <el-select
                  v-model="formData.crewId"
                  placeholder="请选择班组"
                  @change="changeCrew"
                  clearable
                >
                  <el-option
                    v-for="item in crewList"
                    :key="item.id"
                    :label="item.crewName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="设备" prop="equipId">
                <el-select
                  v-model="formData.equipId"
                  placeholder="请选择设备"
                  @change="changEquip"
                  clearable
                >
                  <el-option
                    v-for="item in equipList"
                    :key="item.id"
                    :label="item.equipName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <h4 class="mb-[20px] mt-[20px]">详细数据</h4>
        <el-card shadow="never" class="table-container">
          <template #header v-if="!props.isReadonly">
            <el-button type="success" plain @click="handleAdd">
              <i-ep-plus />
              新增</el-button
            >
          </template>
          <div class="formTable">
            <el-table
              :data="formData.details"
              style="width: 100%"
              :key="Math.random"
              border
            >
              <el-table-column
                type="index"
                label="序号"
                align="center"
                width="100"
              />
              <el-table-column label="计划班次" props="shiftId" min-width="95">
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.shiftId'"
                    :rules="rules.sonshiftId"
                    label-width="0"
                  >
                    <el-select
                      v-model="row.shiftId"
                      placeholder="请输入计划班次"
                      clearable
                      style="width: 170px"
                    >
                      <el-option
                        v-for="item in shiftList"
                        :key="item.id"
                        :label="item.shiftCode"
                        :value="item.shiftId"
                      />
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="计划人员"
                props="planUsers"
                min-width="240"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.planUserIds'"
                    :rules="rules.sonplanUserIds"
                    label-width="0"
                  >
                    <el-select
                      v-if="!props.isReadonly"
                      v-model="row.memberIds"
                      placeholder="请选择计划人员"
                      clearable
                      style="width: 480px"
                      @change="changePlanUser(row)"
                      filterable
                      multiple
                      collapse-tags-tooltip
                      :max-collapse-tags="5"
                    >
                      <el-option
                        v-for="item in memberList"
                        :key="item.id"
                        :label="`${item.memberName}`"
                        :value="item.memberId"
                      />
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="计划数量"
                props="planQuantity"
                min-width="100"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.planQuantity'"
                    :rules="rules.sonplanQuantity"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.planQuantity"
                      placeholder="请输入计划数量"
                      clearable
                    />
                    <span v-else>{{ row.planQuantity }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <!--<el-table-column
                label="计划人员s"
                props="planUserIds"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.planUserIds'"
                    :rules="rules.sonplanUserIds"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.planUserIds"
                      placeholder="请输入计划人员s"
                      clearable
                    />
                    <span v-else>{{ row.planUserIds }}</span>
                  </el-form-item>
                </template>
              </el-table-column>-->
              <el-table-column
                fixed="right"
                align="center"
                label="操作"
                width="100"
                v-if="!props.isReadonly"
              >
                <template #default="scope">
                  <el-button
                    :disabled="formData.details.length < 2"
                    type="danger"
                    link
                    @click.stop="handleDelete(scope.$index)"
                    ><i-ep-delete />
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MESMESCOREMONTHPLANACTUALADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  organizationId: "",
  organizationCode: "",
  organizationName: "",
  plantId: "",
  plantCode: "",
  plantName: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  sandCoreNumber: "",
  allTotal: "",
  pm: "",
  ms: "",
  coreState: "",
  equipModel: "",
  sandModel: "",
  demandPeople: "",
  planId: "",
  planQuantity: "",
  finishQuantity: "",
  status: "",
  requireDate: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
  shiftSetId: "",
  shiftSetName: "",
  crewId: "",
  crewName: "",
  totalTime: "",
  workingFormList: [],
  details: [
    {
      id: "",
      organizationId: "",
      organizationCode: "",
      plantId: "",
      organizationName: "",
      plantCode: "",
      plantName: "",
      monthPlanId: "",
      processesId: "",
      processesClassification: "",
      sequence: "",
      figureNumber: "",
      planQuantity: "",
      plannedBatch: "",
      finishQuantity: "",
      validQuantity: "",
      invalidQuantity: "",
      materialId: "",
      materialCode: "",
      materialName: "",
      scrapQuantity: "",
      quantityUnit: "",
      isClosed: "",
      isPause: "",
      formStatus: "",
      finishTime: "",
      finishUser: "",
      approveTime: "",
      approveUser: "",
      processingOrderNumber: "",
      processingOrderType: "",
      shiftSystemId: "",
      shiftId: "",
      groupsId: "",
      planUserIds: "",
      planUsers: "",
      memberIds: [],
      deviceId: "",
      deviceName: "",
      demandPeople: "",
      planBeginTime: "",
      planEndTime: "",
      beginTime: "",
      endTime: "",
      routingAllocationId: "",
      planDate: "",
      planDateId: "",
      stoveNum: "",
      stoveStatus: "",
      stoveCount: "",
      workCenterId: "",
      workCenterCode: "",
      workCenterName: "",
      version: "",
      remarks: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
      deleted: "",
    },
  ],
});

/** rules规则 */
const rules = reactive({
  materialCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  materialName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  planId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  planQuantity: [],
  finishQuantity: [],
  requireDate: [],
  sonmonthPlanId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  sonplanQuantity: [
    { required: true, message: "请输入计划数量", trigger: "blur" },
    { validator: validateNumber, trigger: "blur" },
  ],
  sonshiftSystemId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  sonshiftId: [{ required: true, message: "请输入班次", trigger: "change" }],
  songroupsId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  sonplanUserIds: [
    { required: true, message: "请输入计划人员", trigger: "change" },
  ],
  sonplanUsers: [],
  shiftSetId: [{ required: true, message: "请输入班制", trigger: "change" }],
  crewId: [{ required: true, message: "请输入班组", trigger: "change" }],
});

const isValidated = ref(false);
/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};

const details = {
  id: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  organizationName: "",
  plantCode: "",
  plantName: "",
  monthPlanId: "",
  processesId: "",
  processesClassification: "",
  sequence: "",
  figureNumber: "",
  planQuantity: "",
  plannedBatch: "",
  finishQuantity: "",
  validQuantity: "",
  invalidQuantity: "",
  materialId: "",
  materialCode: "",
  materialName: "",
  scrapQuantity: "",
  quantityUnit: "",
  isClosed: "",
  isPause: "",
  formStatus: "",
  finishTime: "",
  finishUser: "",
  approveTime: "",
  approveUser: "",
  processingOrderNumber: "",
  processingOrderType: "",
  shiftSystemId: "",
  shiftId: "",
  groupsId: "",
  planUserIds: "",
  planUsers: "",
  memberIds: [],
  deviceId: "",
  deviceName: "",
  demandPeople: "",
  planBeginTime: "",
  planEndTime: "",
  beginTime: "",
  endTime: "",
  routingAllocationId: "",
  planDate: "",
  planDateId: "",
  stoveNum: "",
  stoveStatus: "",
  stoveCount: "",
  workCenterId: "",
  workCenterCode: "",
  workCenterName: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  formData.details.push(sondata);
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      formData.requireDate = formatDate(newVal.requireDate);
      formData.totalTime = newVal.ms * newVal.pm * newVal.planQuantity;
      if (formData.plantId) {
        getEquipList(formData.equipModel);
        getShiftSetList();
        getCrews();
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [JSON.parse(JSON.stringify(details))];
  formData.id = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.organizationName = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.plantName = "";
  formData.materialId = "";
  formData.materialCode = "";
  formData.materialName = "";
  formData.sandCoreNumber = "";
  formData.allTotal = "";
  formData.pm = "";
  formData.ms = "";
  formData.coreState = "";
  formData.equipModel = "";
  formData.sandModel = "";
  formData.demandPeople = "";
  formData.shiftSetId = "";
  formData.shiftSetName = "";
  formData.crewId = "";
  formData.crewName = "";
  formData.totalTime = "";
  formData.planId = "";
  formData.planQuantity = "";
  formData.finishQuantity = "";
  formData.status = "";
  formData.requireDate = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.deleted = "";
  formData.workingFormList = [];
  memberList.value = [];
  shiftList.value = [];
}

const loading = ref(false);

/** 制芯月计划实际表保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      let sum = 0;
      formData.details.forEach((item: any) => {
        sum += Number(item.planQuantity);
      });
      if (sum != formData.planQuantity) {
        ElMessage.error(`计划数量与实际数量不符`);
        return;
      }
      loading.value = true;
      console.log("formData", toRaw(formData));
      formData.workingFormList = formData.details;
      await request({
        url: "/mes/mescoremonthplanactual/saveWorking",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(`制芯工单生成成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

async function getdetails() {
  let sondetails = await request({
    url: "/mes/mescoremonthplanactual/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
}
//时间格式处理，yyyy-mm-dd
function formatDate(date) {
  if (!date) return "";
  return date.split(" ")[0]; // 返回日期的年月日部分，而隐藏时间部分
}
//班制
const shiftSetList = ref([]);
async function getShiftSetList() {
  if (formData.plantId) {
    await request({
      url: "mes/messhiftset/getList",
      method: "post",
      data: { plantId: formData.plantId, enabled: 1 },
    }).then((res) => {
      shiftSetList.value = res.data;
    });
  }
}
function changeShiftSet(val) {
  formData.shiftSetId = val;
  formData.shiftSetName = "";
  shiftList.value = [];
  formData.details.forEach((item) => {
    item.shiftId = "";
  });
  if (val) {
    let shiftSet = shiftSetList.value.find((item) => item.id == val);
    formData.shiftSetName = shiftSet.shiftSetName;
    getShifts();
  }
}
const crewList = ref([]);
async function getCrews() {
  await request({
    url: "mes/mescrew/getCrew",
    method: "post",
    data: {
      plantId: formData.plantId,
      enabled: 1,
    },
  }).then((res) => {
    crewList.value = res.data;
  });
}
function changeCrew(val) {
  formData.crewId = val;
  formData.crewName = "";
  memberList.value = [];
  formData.details.forEach((item) => {
    item.planUserIds = "";
    item.planUsers = "";
    item.memberIds = [];
  });
  if (val) {
    let crew = crewList.value.find((item) => item.id == val);
    formData.crewName = crew.crewName;
    getCrewMembers();
  }
}

function changEquip(val) {
  equipList.value.forEach((item) => {
    if (item.id === val) {
      formData.equipCode = item.equipCode;
      formData.equipName = item.equipName;
    }
  });
  formData.equipId = val;
}

//班次
const shiftList = ref([]);
async function getShifts() {
  await request({
    url: "mes/messhiftset/getDetails",
    method: "post",
    data: {
      id: formData.shiftSetId,
    },
  }).then((res) => {
    shiftList.value = res.data;
  });
}

//人员
const memberList = ref([]);
async function getCrewMembers() {
  await request({
    url: "mes/mescrew/getCrewMembers",
    method: "post",
    data: {
      id: formData.crewId,
    },
  }).then((res) => {
    memberList.value = res.data;
  });
}
//人员
const changePlanUser = (row: any) => {
  row.planUserIds = row.memberIds.join(",");
  let materialNameList = [];
  row.memberIds.forEach((item: any) => {
    memberList.value.forEach((i) => {
      if (item === i.memberId) {
        materialNameList.push(i.memberName);
      }
    });
  });
  row.planUsers = materialNameList.join(",");
};
function validateNumber(rule: any, value: any, callback: (a?: any) => {}) {
  if (isNaN(parseFloat(value)) && isFinite(value)) {
    callback(new Error("请输入数字"));
  } else if (!/^[+-]?\d*(\.\d*)?(e[+-]?\d+)?$/.test(value)) {
    callback(new Error("请输入数字"));
  } else if (Number(value) <= 0) {
    callback(new Error("请输入大于0的值"));
  } else if (!/^[+-]?\d+?(e[+-]?\d+)?$/.test(value)) {
    callback(new Error("请输入整数"));
  } else {
    callback();
  }
}

//设备
const equipList = ref([]);
const getEquipList = async (equipModel: String) => {
  const { data } = await request({
    url: "/mdm/mdmequipinfo/getList",
    method: "post",
    data: { equipTypeName: equipModel },
  });
  equipList.value = data;
};
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}

:deep(.el-dialog .el-dialog__body) {
  overflow-y: auto;
  height: 65vh;
}

:deep.el-input.el-input--default.el-input--suffix {
  // 固定宽度
  width: 190px !important;
}

.formTable2 {
  :deep(.el-form-item) {
    margin: 0 0 13px 0 !important;
    width: 100%;
  }
}
:deep(.el-dialog .formTable2 .el-table .el-form-item) {
  padding: 11px 0 0 0 !important;
}
:deep(.el-dialog .formTable2 .el-table .el-form-item__error) {
  font-size: 11px !important;
}

:deep(.el-dialog .formTable2 .el-table) {
  .el-table__body td.el-table__cell {
    // padding: 5px !important;
    padding: 0 !important;
  }
}
</style>
